<template>
  <div class="video">
    <van-nav-bar :title="video.title" left-text="返回" left-arrow @click-left="back" />
    <!-- <video
      v-if="showVideo"
      id="myVideo"
      preload="auto"
      style="width:100%;height:60vw"
      autoplay="true"
    >
      <source :src="video_link" type="application/x-mpegURL" autoplay="true" />
    </video> -->

    <div style="width: 100vw;height:50vw">
          <iframe
          ref="iframe"
          v-show="url_video"
          frameborder="0"
          scrolling="no"
          style="width: 100%;height:100%"
        ></iframe>
    </div>

    <!-- <div
      class="videowrap"
      v-if="!showVideo"
      style="width:100%;height:60vw;background-color:rgba(0,0,0,.5)"
    ></div> -->
    <!-- -->
    <van-row class="btn-group" type="flex" justify="space-between">
      <van-col span="24" style="text-align:center;background: #FFF;padding: 5px;">
        <!-- <van-button
          v-show="video.video_type!=1"
          @click="lastItem"
          size="small"
          type="warning"
          style="margin-left:10px"
        >&lt; 上一集</van-button>
        <van-button
          v-show="video.video_type!=1"
          @click="nextItem"
          size="small"
          type="warning"
          style="margin-left:10px"
        >下一集 &gt;</van-button> -->
        <van-button @click="starVideo" size="small" type="danger" style="margin-left:10px">
          <van-icon name="like" />
          {{starStatus}}
        </van-button>
      </van-col>
    </van-row>

    <app-notice />
    <van-tabs v-model="line_index">
      <van-tab v-for="(item,index) in videoList" :key='index' :title="link_list[index]">
        <div class="cloud-list" v-if="item.length>0">
          <div class="title">
            <van-icon name="live" color="#1989fa" />{{link_list[index]}}
          </div>
          <div class="btn-list">
            <van-button
              :plain="v.video_link!=currentLink"
              size="small"
              v-for="v in item"
              :key="v.video_link"
              type="primary"
              @click="palyVideo(v.video_link)"
            >{{v.link_url_title}}</van-button>
          </div>
        </div>
      </van-tab>
    </van-tabs>

    <van-cell-group style="margin-top:20px;">
      <van-cell>
        <van-row type="flex" justify="center" style="padding-top:10px;   ">
          <van-col span="9" style="padding:0 10px;">
            <!-- <img :src="video.image" alt style="width:100%"> -->
            <iframe
              :src="'img.html?url='+video.image"
              frameborder="0"
              scrolling="no"
              style="width:100%;"
            ></iframe>
          </van-col>
          <van-col span="15" class="video-info">
            <div class="item">
              <span class="key">影片:</span>
              <span class="val">{{ video.title}}</span>
            </div>
            <div class="item">
              <span class="key">演员:</span>
              <span class="val">{{ video.star}}</span>
            </div>
            <div class="item">
              <span class="key">导演:</span>
              <span class="val">{{ video.leader}}</span>
            </div>
            <div class="item">
              <span class="key">年份:</span>
              <span class="val">{{ video.year}}</span>
            </div>
            <div class="item">
              <span class="key">地区:</span>
              <span class="val">{{ video.area}}</span>
            </div>
            <div class="item">
              <span class="key">类型:</span>
              <span class="val">{{ video.type}}</span>
            </div>
            <div class="item">
              <span class="key">发布时间:</span>
              <span class="val">{{video.time_text}}</span>
            </div>
          </van-col>
        </van-row>
      </van-cell>
      <van-cell>
        <div class="desc" style="color:#777">{{video.desc_content}}</div>
      </van-cell>
    </van-cell-group>
    <!-- <app-foot/> -->
  </div>
</template>

<script>
import {
  Icon,
  Cell,
  CellGroup,
  Swipe,
  SwipeItem,
  Button,
  Lazyload,
  NavBar,
  Card,
  Row,
  Col,
  Toast,
  Tabs,
  Tab,
  Popup
} from 'vant';
import Vue from 'vue';
import { setTimeout } from 'timers';
import AppFoot from './component/foot';
import AppNotice from './component/notice';
import Cache from '@/vendor/cache';
import CryptoJS from 'crypto-js';
let isFrom = false;

Vue.use(Lazyload, {
  loading:
    '',
  error:
    ''
});
export default {
  components: {
    [Icon.name]: Icon,
    [Button.name]: Button,
    [Cell.name]: Cell,
    [CellGroup.name]: CellGroup,
    [Swipe.name]: Swipe,
    [SwipeItem.name]: SwipeItem,
    [NavBar.name]: NavBar,
    [Card.name]: Card,
    [Row.name]: Row,
    [Col.name]: Col,
    [Tabs.name]: Tabs,
    [Tab.name]: Tab,
    [Toast.name]: Toast,
    [Popup.name]: Popup,
    AppFoot,
    AppNotice
  },
  data() {
    return {
      basetitle: '',
      video: {
        title: '--',
        image: [],
        video_link: ''
      },
      videoList: {},
      showVideo: false,
      line_index: 0, // 线路索引
      currentLink: undefined,
      starStatus: '未收藏',
      cache: null,
      video_link: '',
      url_video: '',
      link_list: []
    };
  },
  mounted() {
    window.scrollTo(0, 0);
    this.init();
  },
  beforeRouteEnter(to, from, next) {
    next();
    if (from && from.name) {
      isFrom = true;
    }
  },
  beforeRouteUpdate(to, from, next) {
    next();
    this.init();
  },
  methods: {
    init() {
      this.cache = new Cache();
      let list = this.cache.getAllStar();
      if (list[this.$route.params.id]) {
        this.starStatus = '已收藏';
      }
      Toast.loading({ mask: false, loadingType: 'spinner', duration: 0 });
      let cid = encodeURIComponent(
        this.secret(this.$route.params.id, 'w9M0mU6vQwgmoLjY')
      );
      cid = cid.replace(/%/g, '_');
      this.getVideoByCid(cid).then(res => {
        this.video = res.video;
        this.basetitle = this.video['title'];
        document.title = '小V影视-' + this.video.title;
        this.videoList = res.video_resource;
        this.link_list = res.res_list;
        this.showVideo = true;
        this.setCurrentLink();
        this.setVideoRecord();
        Toast.clear();
      });
    },
    setCurrentLink() {
      let arr = this.cache.getAllRecord();
      let record = arr[this.$route.params.id];
      if (record && record.hasOwnProperty('line_index')) {
        this.line_index = record.line_index;
        this.currentLink = record['currentLink'];
      } else {
        this.currentLink = this.videoList[this.line_index][0].video_link;
      }
      this.palyVideo(this.currentLink);
    },
    setVideoRecord() {
      let item_title = '';
      for (let i in this.videoList) {
        this.videoList[i].forEach(vo => {
          if (vo['video_link'] == this.currentLink) {
            item_title = vo['link_url_title'];
          }
        });
      }
      let record = {
        title: this.video['title'],
        image: this.video['image'],
        currentLink: this.currentLink,
        line_index: this.line_index,
        item_title: item_title,
        time: new Date().getTime()
      };
      this.cache.setRecord(this.$route.params.id, record);
    },
    back() {
      if (isFrom) this.$router.go(-1);
      else {
        // 返回上一层
        this.$router.push('/');
      }
    },
    // nextItem() {
    //   for (let i in this.videoList) {
    //     for (let index = 0; index < this.videoList[i].length; index++) {
    //       let item = this.videoList[i][index];
    //       if (item["video_link"] === this.currentLink) {
    //         if (index + 1 <= this.videoList[i].length - 1) {
    //           let link = this.videoList[i][index + 1]["video_link"];
    //           this.palyVideo(link);
    //           return;
    //         } else {
    //           this.palyVideo(this.videoList[i][0]["video_link"]);
    //           return;
    //         }
    //       }
    //     }
    //   }
    // },
    // lastItem() {
    //   for (let i in this.videoList) {
    //     for (let index = 0; index < this.videoList[i].length; index++) {
    //       let item = this.videoList[i][index];
    //       if (item["video_link"] === this.currentLink) {
    //         if (index - 1 < 0) {
    //           let link = this.videoList[i][this.videoList[i].length - 1][
    //             "video_link"
    //           ];
    //           this.palyVideo(link);
    //           return;
    //         } else {
    //           this.palyVideo(this.videoList[i][index - 1]["video_link"]);
    //           return;
    //         }
    //       }
    //     }
    //   }
    // },
    starVideo() {
      let list = this.cache.getAllStar();
      if (list[this.$route.params.id]) {
        this.cache.setStar(this.$route.params.id, null);
        Toast.success('已取消收藏!');
        this.starStatus = '未收藏';
      } else {
        let star = {
          title: this.video['title'],
          image: this.video['image'],
          time: new Date().getTime()
        };
        this.cache.setStar(this.$route.params.id, star);
        this.starStatus = '已收藏';
        Toast.success('已成功收藏!');
      }
    },
    palyVideo(link) {
      window.scrollTo(0, 0);
      for (let i in this.videoList) {
        for (let index = 0; index < this.videoList[i].length; index++) {
          let item = this.videoList[i][index];
          if (item['video_link'] === link) {
            // Toast.success(`已切换至${item["link_url_title"]}`);
            this.video.title = `${this.basetitle}(${item['link_url_title']})`;
          }
        }
      }
      this.showVideo = false;
      this.currentLink = link;
      this.setVideoRecord();
      setTimeout(() => {
        this.showVideo = true;
        this.video_link = this.secret(link, 'w9M0mU6vQwgmoLjY', true);
        if (/.m3u8|.mp4|.flv/.test(this.video_link)) {
          this.url_video = 'm3u8.html?url=' + this.video_link;
        } else {
          this.url_video = this.video_link;
        }
        this.$refs.iframe.contentWindow.location.replace(this.url_video);
      });
    },

    secret(string, code, operation) {
      code = CryptoJS.MD5(code).toString();
      var iv = CryptoJS.enc.Utf8.parse(code.substring(0, 16));
      var key = CryptoJS.enc.Utf8.parse(code.substring(16));
      if (operation) {
        return CryptoJS.AES.decrypt(string, key, {
          iv: iv,
          padding: CryptoJS.pad.Pkcs7
        }).toString(CryptoJS.enc.Utf8);
      }
      return CryptoJS.AES.encrypt(string, key, {
        iv: iv,
        mode: CryptoJS.mode.CBC,
        padding: CryptoJS.pad.Pkcs7
      }).toString();
    }
  }
};
</script>

<style lang="less">
.video-info {
  .item {
    margin-bottom: 1px;
    font-size: 14px;
    .key {
      color: #333;
    }
    .val {
      color: #999;
    }
  }
}
.icon {
  text-align: right;
  span.time {
    margin-right: 3px;
    font-size: 14px;
    color: #999;
  }
  span.like {
    margin-right: 3px;
    font-size: 14px;
    color: #f00;
  }
  span.fire {
    margin-right: 3px;
    font-size: 14px;
    color: darkred;
  }
}
.video {
  .head {
    width: 100%;
    height: 55px;
    line-height: 55px;
    position: fixed;
    top: 0;
    left: 0;
    z-index: 10;
    background: #fff;
    span.title {
      font-size: 16px;
      margin-left: 20px;
    }
    span.back {
      font-size: 16px;
      padding: 5px 10px;
    }
  }
  video {
    width: 100%;
  }

  &-swipe {
    margin-top: 55px;
    img {
      width: 100%;
      height: 67vw;
    }
  }

  &-title {
    font-size: 16px;
  }

  &-price {
    color: #f44;
  }

  &-express {
    color: #999;
    font-size: 12px;
    padding: 5px 15px;
  }

  &-cell-group {
    margin: 15px 0;

    .van-cell__value {
      color: #999;
    }
  }

  &-tag {
    margin-left: 5px;
  }
}

.cloud-list {
  margin: 10px;
  .btn-list {
    max-height: 240px;
    overflow-y: scroll;

    &::-webkit-scrollbar-track-piece {
      background-color: rgba(0, 0, 0, 0);
      border-left: 1px solid rgba(0, 0, 0, 0);
    }
    &::-webkit-scrollbar {
      width: 6px;
      height: 13px;
      -webkit-border-radius: 5px;
      -moz-border-radius: 5px;
      border-radius: 5px;
    }
    &::-webkit-scrollbar-thumb {
      background-color: rgba(0, 0, 0, 0.5);
      background-clip: padding-box;
      -webkit-border-radius: 5px;
      -moz-border-radius: 5px;
      border-radius: 5px;
      min-height: 28px;
    }
    &::-webkit-scrollbar-thumb:hover {
      background-color: rgba(0, 0, 0, 0.5);
      -webkit-border-radius: 5px;
      -moz-border-radius: 5px;
      border-radius: 5px;
    }

    margin-top: 10px;
    button {
      width: 65px !important;
      margin: 2px;
      padding: 0;
      overflow: hidden;
    }
  }
}
</style>
